import 'dart:async';
// import 'dart:ffi';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:study_demo/base/BaseController.dart';

class NetworkController extends BaseController {
  late StreamSubscription<List<ConnectivityResult>> subscription;

  final netState = ConnectivityResult.none.obs;

  @override
  void onInit() {
    super.onInit();
    subscription = Connectivity()
        .onConnectivityChanged
        .listen((List<ConnectivityResult> result) {
      _onNetChanged(result);
    });
  }

  _onNetChanged(List<ConnectivityResult> event) {
    netState.value = event.first;
    if (netState.value == ConnectivityResult.none) {
//      Toast.show('网络连接断开', Get.overlayContext, duration: Toast.LENGTH_LONG);
      Get.showSnackbar(GetSnackBar(
          messageText: Text('网络连接已断开', style: TextStyle(color: Colors.black54)),
          icon: Icon(Icons.warning, color: Colors.red),
          backgroundColor: Color(0xffFEEDED),
          snackPosition: SnackPosition.TOP));
    } else {
      if (Get.isSnackbarOpen) {
        Get.back();
      }
    }
  }

  @override
  void onClose() {
    super.onClose();
    subscription.cancel();
  }
}
